package dryven.model.binding.fieldset;

import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import dryven.reflection.DeclaringMethodIterator;

public class FieldGroup {
	private FieldSet _set;
	private String _nameKey;
	private List<Field> _fields = new LinkedList<Field>();
	
	protected FieldGroup(String nameKey, FieldSet set) {
		_set = set;
		_nameKey = nameKey;
	}
	
	public String getNameKey() {
		return _nameKey;
	}
	
	public FieldGroup add(Field ... fields) {
		for (Field field : fields) {
			_fields.add(field);
		}
		return this;
	}
	
	public FieldGroup addAllMethodFields(Class<?> modelClass) {
		for (Method method : new DeclaringMethodIterator(modelClass)) {
			if(MethodField.isGetterMethod(method)) {
				_fields.add(new MethodField(method, MethodField.getSetterForGetter(method)));
			}
		}
		return this;
	}
	
	public FieldGroup remove(Field ... fields) {
		for (Field fieldToRemove : fields) {
			ListIterator<Field> it = _fields.listIterator();
			while(it.hasNext()) {
				Field field = it.next();
				if(field.equals(fieldToRemove)) {
					it.remove();
				}
			}
		}
		return this;
	}
	
	public FieldGroup group(String nameKey) {
		return _set.group(nameKey);
	}
	
	public FieldGroup getDefaultGroup() {
		return _set.getDefaultGroup();
	}
	
	public Iterable<Field> getFields() {
		return _fields;
	}
	
	public FieldGroup add(FieldGroup group) {
		return this;
	}
	
	public FieldSet finishGroup() {
		return _set;
	}
	
	public Field findField(Field f) {
		for (Field ff : getFields()) {
			if(ff.equals(f)) {
				return ff;
			}
		}
		return null;
	}
}
